<template>
  <view class="container">
    <u-navbar
      :is-fixed="true"
      :border-bottom="false"
      :is-back="true"
      :background="{ background: '#5697F1' }"
      title="未完成"
      title-color="#fff"
    >
    </u-navbar>
    <u-toast ref="uToast" />

    <view class="tickets">
      <view class="each">
        <view class="row">
          <view class="block">
            <view class="cn">{{ ticket.start }}</view>
            <view>{{ ticket.startTime }}</view>
          </view>
          <view class="block">
            <view class="cn">{{ ticket.name }}</view>
            <view>历时{{ ticket.totalTime }}</view>
          </view>
          <view class="block">
            <view class="cn">{{ ticket.end }}</view>
            <view>{{ ticket.endTime }}</view>
          </view>
        </view>
      </view>
      <view class="each-p" v-for="(p, pIndex) in peoples" :key="pIndex">
        <view class="head">
          <view class="name">{{ p.realname }}</view>
          <view class="name typeF" v-if="p.examine === 'true'">{{
            p.typeF
          }}</view>
        </view>
        <view class="cardno cardtype">{{ p.cardtypeF }}</view>
        <view class="cardno">{{ p.cardno }}</view>
      </view>
    </view>
    <view class="bottom">
      <view class="price" v-if="!oldOption.id">
        <text class="totalCn"
          >总金额：<text class="totalQ">{{ totalPrice }}元</text></text
        >
      </view>
      <view class="price" v-if="oldOption.id">
        <view class="totalCn"
          >原票价：<text class="totalQ">{{ priceOld }}元</text></view
        >
        <view class="totalCn"
          >现票价：<text class="totalQ">{{ totalPrice }}元</text></view
        >
        <view class="totalCn" v-if="Number(priceOld) > Number(totalPrice)"
          >退差价：<text class="totalQ">{{ (Number(priceOld) - Number(totalPrice)).toFixed(2) }}元</text></view
        >
        <view class="totalCn" v-if="Number(totalPrice) > Number(priceOld)"
          >补差价：<text class="totalQ">{{ (Number(totalPrice) - Number(priceOld)).toFixed(2) }}元</text></view
        >
      </view>
      <view class="btns">
        <button class="cancel btn" @click="doCancel">取消订单</button>
        <button class="submit btn" @click="commit">立即支付</button>
      </view>
    </view>
  </view>
</template>

<script>
import moment from "moment";
import { addOrder, updateOrder } from "../../api/system/api";
export default {
  data() {
    return {
      station: {},
      mode: "date",
      show: false,
      today: moment().format("YYYY-MM-DD"),
      ticket: {},
      curIndex: 0,
      ticket: {},
      peoples: [],
      cardtypeList: [
        "中国居民身份证",
        "港澳居民来往内地通行证",
        "台湾居民来往大陆通行证",
        "护照",
      ],
      typeList: ["成人", "儿童", "学生", "残军"],
      totalPrice: 0,
      userInfo: {},
      option: {},
      oldOption: {},
      priceOld: 0
    };
  },
  onLoad(option) {
    this.option = JSON.parse(option.data);
    console.log(this.option)
    if (this.option.option && this.option.option.id) {
      this.oldOption = this.option.option
      this.priceOld = this.oldOption.passangers.reduce((a, b) => {
        return a + Number(b.price)
      }, 0)
      this.priceOld = this.priceOld.toFixed(2)
    }
    this.peoples = JSON.parse(option.data).peoples;
    this.peoples.forEach((v, i) => {
      this.peoples[i].cardtypeF =
        this.cardtypeList[Number(this.peoples[i].cardtype)];
      this.peoples[i].typeF = this.typeList[Number(this.peoples[i].pType)];
      this.peoples[i].price = this.typeList[Number(this.peoples[i].pType)];
    });
    // 计算总票价
    this.ticket = JSON.parse(option.data).ticket;
    let danjia = this.ticket.seats[JSON.parse(option.data).curIndex].price;
    for (let item of this.peoples) {
      if (item.pType !== "0" && item.examine === "true") {
        let discount = 1;
        if (this.option.curIndex === 3) {
          discount = 1;
        } else if (this.option.curIndex === 2) {
          discount = 0.8;
        } else {
          discount = 0.5;
        }
        this.totalPrice += danjia * discount;
        item.price = (danjia * discount).toFixed(2);
      } else {
        this.totalPrice += danjia;
        item.price = danjia;
      }
    }
    this.userInfo = JSON.parse(option.data).userInfo;
    this.totalPrice = this.totalPrice.toFixed(2);
  },
  methods: {
    // 立即支付
    commit() {
      if (this.option.ticket.option.id) {
        updateOrder(this.option.ticket.option.id, {
          trainName: this.option.ticket.name,
          trainType: this.option.ticket.type,
          startStation: this.option.ticket.start,
          endStation: this.option.ticket.end,
          startTime: this.option.ticket.startTime,
          endTime: this.option.ticket.endTime,
          totalTime: this.option.ticket.totalTime,
          status: "已改签",
          userId: this.option.userInfo.id,
          username: this.option.userInfo.realname,
          orderTime: moment().format("YYYY-MM-DD HH:mm:ss"),
          passangers: JSON.stringify(this.peoples),
          seatInfo: this.ticket.seats[this.option.curIndex].name,
          ticketTime: this.option.ticket.tickTime,
        }).then(res => {
          if (res.code === 200) {
            this.$refs.uToast.show({
              title: "改签成功~",
              type: "success",
            });
            setTimeout(() => {
              uni.switchTab({ url: `/pages/home/home` });
            }, 1000);
          }
        })
      } else {
        addOrder({
          trainName: this.option.ticket.name,
          trainType: this.option.ticket.type,
          startStation: this.option.ticket.start,
          endStation: this.option.ticket.end,
          startTime: this.option.ticket.startTime,
          endTime: this.option.ticket.endTime,
          totalTime: this.option.ticket.totalTime,
          status: "已支付",
          no: this.randomStr(10),
          userId: this.option.userInfo.id,
          username: this.option.userInfo.realname,
          orderTime: moment().format("YYYY-MM-DD HH:mm:ss"),
          passangers: JSON.stringify(this.peoples),
          seatInfo: this.ticket.seats[this.option.curIndex].name,
          ticketTime: this.option.ticket.tickTime,
        }).then((res) => {
          if (res.code === 200) {
            this.$refs.uToast.show({
              title: "支付成功~",
              type: "success",
            });
            setTimeout(() => {
              uni.switchTab({ url: `/pages/home/home` });
            }, 1000);
          }
        });
      }
    },
    doCancel() {
      uni.navigateBack({
        delta: 1,
      });
    },
    randomStr(len) {
      let _charStr =
          "abacdefghjklmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ0123456789",
        min = 0,
        max = _charStr.length - 1,
        _str = ""; //定义随机字符串 变量
      //判断是否指定长度，否则默认长度为15
      len = len || 15;
      //循环生成字符串
      for (var i = 0, index; i < len; i++) {
        index = (function (randomIndexFunc, i) {
          return randomIndexFunc(min, max, i, randomIndexFunc);
        })(function (min, max, i, _self) {
          let indexTemp = Math.floor(Math.random() * (max - min + 1) + min),
            numStart = _charStr.length - 10;
          if (i == 0 && indexTemp >= numStart) {
            indexTemp = _self(min, max, i, _self);
          }
          return indexTemp;
        }, i);
        _str += _charStr[index];
      }
      return _str;
    },
  },
};
</script>

<style lang="scss" scoped>
.container {
  background-color: #f1ebeb;
  min-height: 100vh;
  overflow: hidden;
  padding: 2rpx;
}
.station {
  display: flex;
  width: 50%;
  margin: 0 auto;
  align-items: center;
  font-size: 40rpx;
  justify-content: space-around;
  font-weight: bold;
  .img {
    width: 50rpx;
    height: 50rpx;
  }
}
.date {
  display: flex;
  padding: 30rpx 60rpx 0 60rpx;
  font-size: 30rpx;
  justify-content: space-between;

  .img {
    width: 60rpx;
    height: 60rpx;
  }
}
.row {
  margin: 0 auto;
  width: 50%;
  text-align: center;
}
.tickets {
  padding: 20rpx;
  width: calc(100% - 60rpx);
  margin: 30rpx auto;
  background: #fff;
  .each {
    border-radius: 12rpx;
    .row {
      display: flex;
      width: 100%;
      justify-content: space-between;
      font-size: 30rpx;
      font-weight: bold;
      padding: 20rpx 0;
      border-bottom: 1rpx solid #e4dada;
      .cn {
        font-size: 26rpx;
        margin-bottom: 10rpx;
      }
    }
  }
}
.each-p {
  padding-bottom: 20rpx;
  border-bottom: 1rpx solid #e4dada;
  .head {
    display: flex;
    width: 100%;
    gap: 20rpx;
    font-weight: bold;
    margin-top: 20rpx;
    align-items: center;
  }
  .cardno {
    margin-top: 10rpx;
  }
}
.bottom {
  position: fixed;
  bottom: 10rpx;
  width: 100%;
  padding: 0 30rpx;
  left: 30rpx;
  .price {
    width: 100%;
    margin-bottom: 20rpx;
  }
  .btns {
    display: flex;
    width: 100%;
    margin: auto;
    justify-content: space-between;
    .submit {
      background: #e6803a;
      color: #fff;
    }
    .btn {
      font-size: 26rpx;
      height: 80rpx;
      line-height: 80rpx;
    }
  }
}
.cardtype {
  color: #a99e9e;
}
.name {
  font-size: 32rpx;
}
.typeF {
  border: 1rpx solid lightblue;
  padding: 5rpx 10rpx;
  font-size: 25rpx;
  font-weight: normal;
}
.totalCn {
  font-size: 20rpx;
  color: gray;
}
.totalQ {
  font-size: 30rpx;
  color: orange;
}
</style>
